package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //1.输入手机和密码正常登录
        //1.1 获取用户输入的手机号和密码
        if (! StringUtils.isEmpty(loginDto.getPassword()) && !StringUtils.isEmpty(loginDto.getPhone())){
            //1.2 查询用户
            LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApUser::getPhone,loginDto.getPhone());
            ApUser apUser = getOne(wrapper);
            if (apUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //1.3 比对用户名密码
            //获取密码
            String pswd = loginDto.getPassword();
            //获取盐
            String salt = apUser.getSalt();

            pswd = DigestUtils.md5DigestAsHex((pswd + salt).getBytes());
            //比较密码是否一样
            if (!pswd.equals(apUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //1.4 返回jwt
            HashMap<String, Object> map = new HashMap<>();
            map.put("taken", AppJwtUtil.getToken(apUser.getId().longValue()));
            //将盐和密码设置为空
            apUser.setSalt("");
            apUser.setPassword("");

            map.put("user",apUser);
            //返回登录结果
            return ResponseResult.okResult(map);
        }else {//2.游客登录
            //返回jwt id = 0
            HashMap<String, Object> map = new HashMap<>();
            map.put("taken",0L);
            return ResponseResult.okResult(map);
        }
    }
}
